import {
  User,
  UserFilter,
  CreateUserRequest,
  UpdateUserRequest,
  PaginatedResponse,
  ApiResponse,
} from '@/types';

// 用户服务类
class UserService {
  private baseUrl = '/api/users';

  // 获取用户列表
  async getUsers(params: UserFilter & { page?: number; pageSize?: number } = {}): Promise<PaginatedResponse<User>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch users: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取单个用户详情
  async getUser(id: string): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 创建用户
  async createUser(data: CreateUserRequest): Promise<ApiResponse<User>> {
    const response = await fetch(this.baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to create user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新用户
  async updateUser(id: string, data: UpdateUserRequest): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 删除用户
  async deleteUser(id: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to delete user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 批量删除用户
  async batchDeleteUsers(ids: string[]): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/batch`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ids }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to batch delete users: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 重置用户密码
  async resetPassword(id: string, newPassword?: string): Promise<ApiResponse<{ password: string }>> {
    const response = await fetch(`${this.baseUrl}/${id}/reset-password`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ newPassword }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to reset password: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 修改用户密码
  async changePassword(id: string, oldPassword: string, newPassword: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}/change-password`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ oldPassword, newPassword }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to change password: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 分配角色
  async assignRoles(id: string, roleIds: string[]): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}/roles`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ roleIds }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to assign roles: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 分配部门
  async assignDepartments(id: string, departmentIds: string[]): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}/departments`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ departmentIds }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to assign departments: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 分配岗位
  async assignPositions(id: string, positionIds: string[]): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}/positions`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ positionIds }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to assign positions: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取用户权限
  async getUserPermissions(id: string): Promise<ApiResponse<string[]>> {
    const response = await fetch(`${this.baseUrl}/${id}/permissions`);
    if (!response.ok) {
      throw new Error(`Failed to fetch user permissions: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取用户登录历史
  async getUserLoginHistory(id: string): Promise<ApiResponse<any[]>> {
    const response = await fetch(`${this.baseUrl}/${id}/login-history`);
    if (!response.ok) {
      throw new Error(`Failed to fetch user login history: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 锁定用户
  async lockUser(id: string, reason?: string): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}/lock`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ reason }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to lock user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 解锁用户
  async unlockUser(id: string): Promise<ApiResponse<User>> {
    const response = await fetch(`${this.baseUrl}/${id}/unlock`, {
      method: 'POST',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to unlock user: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 上传用户头像
  async uploadAvatar(id: string, file: File): Promise<ApiResponse<{ avatar: string }>> {
    const formData = new FormData();
    formData.append('avatar', file);

    const response = await fetch(`${this.baseUrl}/${id}/avatar`, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to upload avatar: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 批量导入用户
  async importUsers(file: File, organizationId?: string): Promise<ApiResponse<{ success: number; failed: number; errors: string[] }>> {
    const formData = new FormData();
    formData.append('file', file);
    if (organizationId) {
      formData.append('organizationId', organizationId);
    }

    const response = await fetch(`${this.baseUrl}/import`, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to import users: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 导出用户数据
  async exportUsers(params: UserFilter = {}): Promise<Blob> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}/export?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to export users: ${response.statusText}`);
    }
    
    return response.blob();
  }

  // 启用两步验证
  async enableTwoFactor(id: string): Promise<ApiResponse<{ qrCode: string; secret: string }>> {
    const response = await fetch(`${this.baseUrl}/${id}/two-factor/enable`, {
      method: 'POST',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to enable two-factor: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 禁用两步验证
  async disableTwoFactor(id: string, code: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}/two-factor/disable`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ code }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to disable two-factor: ${response.statusText}`);
    }
    
    return response.json();
  }
}

// 导出单例实例
export const userService = new UserService();
export default userService;